<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" title="生鲜采购" color="#000000" backgroundColor="#FFFFFF" :storeName="sUserStoreName"
                :storeId="sUserStore" :option="nbOption" @menuFunc="onClickMenuFunc" @onClickStore="clickRight('storeId')"/>
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="true">
        <template v-slot:searchFields>
          <view class="search-fields">
            <eui-card-input v-model="formData.c_id" title="单据号" placeholder="请输入单据号" type="text"
                            :displayable="displayable"/>
            <eui-card-input v-model="formData.c_status" title="单据状态" placeholder="请选择单据状态"
                            :range="statusList" type="multi"/>
            <eui-card-input v-model="formData.c_dc_wno" title="配送仓库" placeholder="请选择仓库" type="textname"
                            right-icon-type="right" :displayable="displayable" @icon-click="clickRight('wno')"
                            :name="formData.c_dc_wname"/>
            <eui-card-input v-model="formData.c_pl_no" title="采购地" placeholder="请选择采购地" type="textname"
                            right-icon-type="right" :displayable="displayable" @icon-click="selector('plno')"
                            :name="formData.c_pl_name"/>
            <eui-card-input v-model="formData.c_buyer_no" title="采购员" placeholder="请选择采购员" type="textname"
                            right-icon-type="right" :displayable="displayable" @icon-click="clickRight('user')"
                            :name="formData.c_buyer_name"/>
            <eui-card-input v-model="formData.c_delivery_dt_s" title="配送开始日期" placeholder="请选择开始日期"
                            type="date" :displayable="displayable" right-icon-type="clear"
                            @icon-click="clearDate('dtS')"/>
            <eui-card-input v-model="formData.c_delivery_dt_e" title="配送结束日期" placeholder="请选择结束日期"
                            type="date" :displayable="displayable" right-icon-type="clear"
                            @icon-click="clearDate('dtE')"/>
            <view class="bottom flex-1 flex">
              <eui-button type="max2" title="重置" singleTag="reset" @buttonClick="confirm"></eui-button>
              <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm"></eui-button>
            </view>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="main-view" :style="{ height: '300rpx' }">
      <eui-virtual-list @onRefresh="getData" @lower="templateLower" refresher="true" @itemClick="onClickGoToDetail"
                        :origList="dataList" isBottom="true" type="list">
        <template v-slot:list="scope">
          <eui-text title="配送中心" :value="scope.c_dc_store_id"
                    :name="getRelatedName('rdsStores', scope.c_dc_store_id)" type="titlename2" cWidth="width: 100%"/>
          <eui-text title="配送仓库" :value="scope.c_dc_wno" :name="getRelatedName('rdsWnos', scope.c_dc_wno)"
                    type="titlename2"/>
          <eui-text title="部门" :value="scope.c_adno" :name="getRelatedName('rdsDeparts', scope.c_adno)"
                    type="titlename2"/>
          <eui-text title="目的机构" :value="scope.c_d_store_id" :name="getRelatedName('rdsStores', scope.c_d_store_id)"
                    type="titlename2"/>
          <eui-text title="配送日期" :value="scope.c_delivery_dt" type="date"/>
          <eui-text title="采购地" :value="scope.c_pl_no" :name="getFreshLocationName(scope.c_pl_no)"
                    type="titlename2"/>
          <eui-text title="采购员" :value="scope.c_buyer_no" :name="getRelatedName('rdsUsers', scope.c_buyer_no)"
                    type="titlename2"/>
          <eui-text title="录入" :value="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)"
                    type="titlename2"/>
          <eui-text :value="scope.c_mk_dt" type="rdstime2"/>
          <eui-text title="审核" :value="scope.c_au_userno" :name="getRelatedName('rdsUsers', scope.c_au_userno)"
                    type="titlename2" v-if="scope.c_status === '3'"/>
          <eui-text :value="scope.c_au_dt" type="rdstime2" v-if="scope.c_status === '3'"/>
        </template>
        <template v-slot:bottom="scope">
          <view v-if="['3', '8', '9'].includes(scope.c_status)">
            <eui-button :modelValue="scope" type="min" single-tag="detail" title="详情" @buttonClick="operate"/>
          </view>
          <view v-if="scope.c_status === '0'">
            <eui-button :modelValue="scope" type="min2" single-tag="edit" title="编辑" @buttonClick="operate"/>
          </view>
          <view v-if="scope.c_status === '0'">
            <eui-button :modelValue="scope" type="min" single-tag="audit" title="审核" @buttonClick="operate"/>
          </view>
        </template>
      </eui-virtual-list>
    </view>
  </view>
</template>

<script setup type="ts">

import {ref} from "vue";
import {getRdsUrl, rdsRequest,} from '@/hooks/rdsServices';
import Enjoy from "@/common/enjoy";
import {validateStores} from "@/hooks/useValidateMethod";
import {onLoad} from "@dcloudio/uni-app";
import {init} from "@/hooks/init";
import dateRangUtil from '../../../common/dateRangUtil';
import {getRelatedName, getDictSelectList, getFreshLocationName} from '../components/RelatedName.js';
import {useMainStore} from "@/store/modules/store";
import service from '../../../common/service';

const rdsUrl = getRdsUrl();
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const nbOption = ref({
  items: [
    {title: '新增单据', onClick: 'onClickNewCount', icon: 'plusempty'},
  ]
});
const statusList = ref([]);
const searchText = ref('');
const formData = ref({
  c_delivery_dt_s: (dateRangUtil.getLast1Month())[0],
  c_delivery_dt_e: (dateRangUtil.getLast1Month())[1],
  c_status: '',
  c_id: '',
  c_dc_wno: '',
  c_dc_wname: '',
  c_adno: '',
  c_pl_no: '',
  c_pl_name: '',
  c_buyer_no: '',
  c_buyer_name: '',
});
const displayable = ref(false);
const CurrentPage = ref(1);
const PageSize = ref(10);
const RowsCount = ref(0);
const PageCount = ref(1);
const dataList = ref([]);
const mainStore = useMainStore();
const RdsSearchBar = ref(null);
const EuiNavBar = ref(null);

onLoad(async () => {
  await init();
  await initRdsPlNos();
  statusList.value = getDictSelectList('PO类单据状态');
  const {loginInfo} = mainStore;
  if (!loginInfo.sUserStore) {
    EuiNavBar.value.onClickStore();
    return;
  }
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  await getData();
});

const initRdsPlNos = async () => {
  let rdsPlNos = service.getLocalStorage('rdsFreshLocation');
  if (rdsPlNos) return;
  service.enjoyShowLoading('正在加载档案...');
  const req = {
    IsNotPage: true,
    CurrentPage: 1,
    PageSize: 100,
    BillType: "",
    WhereList: []
  };
  const result = await rdsRequest(rdsUrl.bcApi, '生鲜采购地维护', 'EnjoyQueryList', req);
  service.addlocalStorage("rdsFreshLocation", result.ReturnObject);
  service.enjoyHideLoading();
}

const onClickMenuFunc = async (e) => {
  switch (e) {
    case 'onClickNewCount':
      setTimeout(() => {
        EuiNavBar.value.closeDrawer();
      }, 1200);
      // 检查当前机构是否为 分店或配送中心，否则不允许新建
      const result = await validateStores(
          {fieldName: 'c_store_id', newValue: sUserStore.value},
          {ischecklimit: true, firstValueMode: true}
      );
      if (!['2', '3'].includes(result.c_type)) {
        uni.showToast({
          title: '当前机构不允许新建补货单,请切换至分店或配送中心!',
          icon: 'none',
          duration: 3000,
        });
        return;
      }
      await uni.navigateTo({
        url: './edit?storeId=' + sUserStore.value
      });
      break;
  }
}

const clickRight = (type) => {
  const params = Enjoy.GetDialogParms();
  params.CallBack = ChangeCallBack;
  if (type == 'storeId') {
    params.SelectionType = '机构选择';
    params.SelectedItems = sUserStore.value;
  } else if (type == 'wno') {
    params.SelectionType = '仓库选择';
    params.SelectedItems = formData.value.c_dc_wno;
    params.SelectionStoreId = sUserStore.value;
  } else if (type == 'user') {
    params.SelectionType = '人员选择';
    params.SelectedItems = formData.value.c_buyer_no;
  }
  Enjoy.OpenDialog(params);
}

const ChangeCallBack = async (event) => {
  if (event.SelectionType == '机构选择') {
    // 更新机构信息
    sUserStoreName.value = event.BackParms.Value;
    sUserStore.value = event.BackParms.Key;
    // 回填全局登录机构
    const {loginInfo} = mainStore;
    loginInfo.sUserStore = sUserStore.value;
    loginInfo.sUserStoreName = sUserStoreName.value;
    // 按新条件获取数据
    await getData();
  } else if (event.SelectionType == '仓库选择') {
    formData.value.c_dc_wno = event.BackParms.Key;
    formData.value.c_dc_wname = event.BackParms.Value;
  } else if (event.SelectionType == '人员选择') {
    formData.value.c_buyer_no = event.BackParms.Key;
    formData.value.c_buyer_name = event.BackParms.Value;
  }
}

const SelectionChanged = async (type, param) => {
  switch (type) {
    case 'wno':
      formData.value.c_dc_wno = param.c_wno;
      formData.value.c_dc_wname = param.c_name;
      break;
    case 'plno':
      formData.value.c_pl_no = param.c_no;
      formData.value.c_pl_name = param.c_name;
      break;
    case 'user':
      formData.value.c_buyer_no = param.c_userno;
      formData.value.c_buyer_name = param.c_name;
      break;

  }
}

const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  searchText.value = e.value;
  await getData();
}

const scanCode = () => {
  uni.scanCode({
    success: function (res) {
      if (res.result != '' && res.result != undefined) {
        searchText.value = res.result;
        getData();
      }
    },
  });
}

const confirm = async (t) => {
  let {singleTag} = t;
  switch (singleTag) {
    case 'reset':
      formData.value.c_delivery_dt_e = (dateRangUtil.getLast1Month())[1];
      formData.value.c_delivery_dt_s = (dateRangUtil.getLast1Month())[0];
      formData.value.c_status = '';
      formData.value.c_id = '';
      formData.value.c_dc_wno = '';
      formData.value.c_dc_wname = '';
      formData.value.c_adno = '';
      formData.value.c_pl_no = '';
      formData.value.c_pl_name = '';
      formData.value.c_buyer_no = '';
      formData.value.c_buyer_name = '';
      break;
    case 'fix':
      await getData();
      // 关闭弹出层
      RdsSearchBar.value.closeDrawer();
      break;
  }
}

const selector = (type) => {
  if (type === 'plno') {
    uni.navigateTo({
      url: `../modals/plno/index`
    });
    return;
  }
  uni.navigateTo({
    url: `../modals/index?type=${type}`
  });
}

const clearDate = (tag) => {
  switch (tag) {
    case 'dtS':
      formData.value.c_delivery_dt_s = null;
      break;
    case 'dtE':
      formData.value.c_delivery_dt_e = null;
      break;
  }
}

const templateLower = async () => {
  if (CurrentPage.value < PageCount.value) {
    CurrentPage.value = CurrentPage.value + 1;
    await getData(true);
  }
}

const onClickGoToDetail = (e) => {
  let {item} = e;
  uni.navigateTo({
    url: './edit?c_id=' + item.c_id + '&storeId=' + sUserStore.value
  });
}

const operate = (e) => {
  let {singleTag, modelValue} = e;

  const req = {
    BillId: modelValue.c_id,
    UserNo: sUser.value,
  }
  switch (singleTag) {
    case 'audit':
      if (['3', '8', '9'].includes(modelValue.c_status)) {
        onClickGoToDetail({item: modelValue});
      } else if (modelValue.c_status == '0') {
        uni.showModal({
          title: ' 提示',
          content: '请确认，审核单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在审核...');
              await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyBillAudit', req, '5C1');
              service.enjoyHideLoading();
              uni.showToast({
                duration: 2000,
                icon: 'none',
                title: ' 审核成功！'
              });
              setTimeout(async () => {
                await getData();
              }, 1000);
            }
          }
        });
      }
      break;
    case 'detail':
    case 'edit':
      onClickGoToDetail({item: modelValue});
      break;
  }
}

const getData = async (e) => {
  if (!e) {
    CurrentPage.value = 1;
  }
  const req = {
    IsNotPage: false,
    CurrentPage: CurrentPage.value,
    PageSize: PageSize.value,
    UserNo: sUser.value,
    WhereList: [
      {c_col: "c_dc_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且"},
      formData.value?.c_delivery_dt_s ? {
        c_col: "c_mk_dt",
        c_oper: "大于等于",
        c_value: formData.value.c_delivery_dt_s,
        c_logic: "而且",
        c_col_dtype: "System.DateTime"
      } : {},
      formData.value?.c_delivery_dt_e ? {
        c_col: "c_mk_dt",
        c_oper: "小于等于",
        c_value: formData.value.c_delivery_dt_e,
        c_logic: "而且",
        c_col_dtype: "System.DateTime"
      } : {},
      formData.value?.c_status ? {
        c_col: "c_status",
        c_oper: "包含",
        c_value: formData.value.c_status,
        c_logic: "而且"
      } : {},
      formData.value?.c_id ? {c_col: "c_id", c_oper: "等于", c_value: formData.value.c_id, c_logic: "而且"} : {},
      formData.value.c_dc_wno ? {
        c_col: "c_dc_wno",
        c_oper: "等于",
        c_value: formData.value.c_dc_wno,
        c_logic: "而且"
      } : {},
      formData.value?.c_pl_no ? {
        c_col: "c_pl_no",
        c_oper: "等于",
        c_value: formData.value.c_pl_no,
        c_logic: "而且"
      } : {},
      formData.value?.c_buyer_no ? {
        c_col: "c_buyer_no",
        c_oper: "等于",
        c_value: formData.value.c_buyer_no,
        c_logic: "而且"
      } : {},
    ]
  }
  if (searchText.value) {
    req.WhereList.push({
      c_col: "c_gcode",
      c_oper: "等于",
      c_value: searchText.value,
      c_logic: "而且",
    });
  }

  const result = await rdsRequest(rdsUrl.scApi, '生鲜采购单', 'EnjoyQueryList', req, '');
  CurrentPage.value = result.CurrentPage; //第几页
  PageSize.value = result.PageSize; //每页10条
  RowsCount.value = result.RowsCount; //总条数
  PageCount.value = result.PageCount; //总页数
  if (result.CurrentPage == 1) {
    dataList.value = result.ReturnObject;
  } else {
    dataList.value = dataList.value.concat(result.ReturnObject);
  }
}

defineExpose({
  SelectionChanged
});
</script>


<style lang="scss" scoped>
@import '../../../main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.top-view {
  width: 100%;
  height: 88rpx;
  background: #FFFFFF;
}

.main-view {
  flex: 1;
  flex-direction: column;
}

.search-fields {
  width: 100%;
  background: #FFFFFF;
  position: relative;

  .bottom {
    background: #ffffff;
    border-top: 1rpx solid $uni-line-color;
    display: flex;
    justify-content: center;
    padding: 20rpx;
  }
}
</style>